/*
 * @(#)AbstractQuery.java
 * 
 * Copyright (c) 2003 DCIVision Ltd
 * All rights reserved.
 * 
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */
package com.dcivision.framework.dao;

import java.util.Iterator;
import java.util.List;
import java.util.Vector;

public abstract class AbstractQuery {

  
  
    
    private StringBuffer query = null;
    private Vector params = null;
    private Vector subQuerys = null;

    private int offset = 1;
    private int start = 0;
    
    public AbstractQuery () {
        this("");
    }

    public AbstractQuery(String s){
        query = new StringBuffer(s);
        params = new Vector();
        params.add(null);
        subQuerys = new Vector();
    }

    public AbstractQuery subQuery ( AbstractQuery subQuery ) {
        query.append(subQuery.toString());
        subQuerys.add(subQuery);
        return this;
    }

    public AbstractQuery append ( String s ) {
        query.append ( s );
        return this;
    }

    public void setParameter ( int index, Object param ) {
        if(params.size() < index+1){
            params.setSize(index+1);
        }
        params.set (index, param);
    }

    public List getAllParameters(){
        return params.subList(1, params.size());
    }

    public int getParameterSize(){
        return params.size()-1;
    }

    public void pack(){
      offset = 1; 
      start = 0;
      
      Iterator subqItr = subQuerys.listIterator();
        while(subqItr.hasNext()){
            SubQuery subQuery = (SubQuery)subqItr.next();
            if(subQuery.getParameterSize()>0){  
              params.addAll ( calculateParameterOffset(subQuery), subQuery.getAllParameters() );
              offset+=subQuery.getParameterSize();
            }
        }
        subQuerys.clear();
    }

    private int calculateParameterOffset(AbstractQuery subQuery){
 
        int end = query.indexOf(subQuery.toString(),start);
        StringBuffer s = new StringBuffer(query.substring(start,end));
        start = end+subQuery.toString().length();
        
        int index;
        while((index=s.indexOf("?"))>-1){
            offset++;
            s.deleteCharAt(index);
        }
        return offset;
    }

    public String toString(){
        return query.toString();
    }
}